import { useEffect, useMemo } from 'react'
import dayjs from 'dayjs'
import { Button, Card, Segmented } from 'antd'

import { CusAgGrid } from '@/components/CusAgGrid'
import { dhFormat } from '@/utils/utils'
import {
  getLogisticsStatusName,
  getPublishStatusName,
  getRouteNodeName,
  getRouteTypeName,
} from '@oBiz/TrackOrder/utils'
import { useBaseInfoBoundStore } from '../BaseInfo'
import { useUrlParams } from '../utils'
import { AddRouteModal } from './AddRouteModal'
import { Cell } from './Cell'
import { IPublishRouteListItem, TCol } from './interface'
import { useBoundStore } from './store'
import { usePublishRouteList } from './usePublishRouteList'
import styles from './styles.module.less'

export const PublishRoute = () => {
  usePublishRouteList() // 放最顶部

  const loading = useBaseInfoBoundStore(v => v.loading)
  const logisticsNodeList = useBaseInfoBoundStore(v => v.waybillInfo?.logisticsNodeList)

  // 清理
  useEffect(() => () => useBoundStore.setState(useBoundStore.getInitialState(), true), [])

  return (
    <Card styles={{ body: { height: 660 } }} loading={loading} title="发布路由">
      {!!logisticsNodeList?.length && <PublishRouteInner logisticsNodeList={logisticsNodeList} />}
    </Card>
  )
}

const jsonValueFormatter = (obj: unknown): string => {
  if (obj == null) return ''
  try {
    return JSON.stringify(obj)
  } catch {
    return ''
  }
}

function PublishRouteInner({ logisticsNodeList }: { logisticsNodeList: number[] }) {
  const { waybillNo } = useUrlParams()
  const defaultLogisticsStatus = useBaseInfoBoundStore(v => v.waybillInfo!.logisticsNodeList[0])
  const archiveFlag = useBaseInfoBoundStore(v => v.waybillInfo?.archiveFlag)
  const getBaseInfoData = useBaseInfoBoundStore(v => v.getData)
  const gridRef = useBoundStore(v => v.gridRef)
  const loading = useBoundStore(v => v.request?.loading)
  const data = useBoundStore(v => v.request?.data)
  const logisticsStatus = useBoundStore(v => v.reqData.logisticsStatus)
  const editingPublishId = useBoundStore(v => v.editingRowData?.publishId)
  const setReqData = useBoundStore(v => v.setReqData)
  const getData = useBoundStore(v => v.getData)

  // 列配置
  const defaultColDef = useMemo<Partial<TCol>>(
    () => ({
      flex: 1,
      minWidth: 130,
      sortable: false,
      cellRenderer: Cell,
      cellClassRules: {
        [styles.is_error]: ({ colDef, value, data }) => {
          if (editingPublishId === data?.publishId) return false
          const { field } = colDef
          if (field === 'occurDate' || field === 'keepDate') {
            const { publishStatus, markFlag } = data || {}
            if (publishStatus === 0 && markFlag !== 1) {
              return !value
            }
          }
          return false
        },
      },
    }),
    [editingPublishId],
  )
  const columnDefs = useMemo(
    () => [
      {
        field: 'routeNo',
        headerName: '路由编号',
        flex: 0.01,
        minWidth: 114,
      } satisfies TCol<'routeNo'>,
      {
        field: 'routeNode',
        headerName: '路由节点',
        valueFormatter: ({ value }) => getRouteNodeName(value) || '',
      } satisfies TCol<'routeNode'>,
      {
        field: 'routeTitle',
        headerName: '路由',
        flex: 2,
        minWidth: 210,
      } satisfies TCol<'routeTitle'>,
      {
        field: 'routeType',
        headerName: '路由类型',
        minWidth: 114,
        valueFormatter: ({ value }) => getRouteTypeName(value) || '',
      } satisfies TCol<'routeType'>,
      {
        field: 'occurDate',
        headerName: '发生时间',
        flex: 0.01,
        minWidth: 190,
        valueFormatter: ({ value: v }) => (v ? dayjs(v).$formatSmart($F_YMDHms) : ''),
      } satisfies TCol<'occurDate'>,
      {
        field: 'keepDate',
        headerName: '持续时间',
        minWidth: 114,
        valueFormatter: ({ value }) => dhFormat(value),
      } satisfies TCol<'keepDate'>,
      {
        field: 'fileList',
        headerName: '附件',
        flex: 2,
        minWidth: 210,
        valueFormatter: ({ value }) => jsonValueFormatter(value),
      } satisfies TCol<'fileList'>,
      {
        field: 'publishStatus',
        headerName: '发布状态',
        minWidth: 114,
        valueFormatter: ({ value }) => getPublishStatusName(value) || '',
      } satisfies TCol<'publishStatus'>,
      {
        field: 'publishId',
        headerName: '操作',
        flex: 0.01,
        width: 100,
        minWidth: 100,
        pinned: 'right',
      } satisfies TCol<'publishId'>,
    ],
    [],
  )

  // 初始化
  useEffect(() => {
    setReqData(defaultLogisticsStatus, waybillNo)
    getData(true)
  }, [defaultLogisticsStatus, getData, setReqData, waybillNo])

  return (
    <div className={styles.box}>
      <div className={styles.header}>
        <div className={styles.header_filter}>
          <Segmented<number>
            options={logisticsNodeList.map(v => ({ label: getLogisticsStatusName(v), value: v }))}
            value={logisticsStatus}
            onChange={v => {
              setReqData(v)
              getData(true)
            }}
          />
        </div>
        <div className={styles.header_action}>
          {archiveFlag === 0 && (
            <Button
              type="primary"
              onClick={() => {
                AddRouteModal.open({
                  waybillNo,
                  onSuccess: () => {
                    getData(true)
                    getBaseInfoData()
                  },
                })
              }}
            >
              添加路由
            </Button>
          )}
        </div>
      </div>
      <div className={styles.main}>
        <CusAgGrid<IPublishRouteListItem>
          ref={gridRef}
          loading={loading}
          rowData={data}
          defaultColDef={defaultColDef}
          columnDefs={columnDefs}
          cellSelection={false}
        />
      </div>
    </div>
  )
}
